package com.ruoyi.framework.security.provider;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.token.WechatAuthenticationToken;
import com.ruoyi.framework.web.service.IWechatDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * @author by dg
 * @date 2023/7/17.
 */
public class WechatAuthenticationProvider implements AuthenticationProvider {

    private IWechatDetailsService userDetailsService;



    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WechatAuthenticationToken wechatAuthenticationToken = (WechatAuthenticationToken) authentication;
        String username = (String) wechatAuthenticationToken.getPrincipal();
        LoginUser user = (LoginUser) userDetailsService.loadUserByUsername(username);
        if (user == null) {
            throw new UserPasswordNotMatchException();
        }
        return new WechatAuthenticationToken(user, user.getPassword(), user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return WechatAuthenticationToken.class.isAssignableFrom(aClass);
    }

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username)
    {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }


    public boolean matches(LoginUser user, String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void setUserDetailsService(IWechatDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
